package com.cpdmali.api.helper;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.SAXException;

import com.cpdmali.api.Exception.InvalidXmlException;
import com.cpdmali.api.jaxb.courrier.DomainsCourrierXsd;
import com.cpdmali.api.jaxb.courrier.ForwardingCourrierXsd;
import com.cpdmali.api.jaxb.courrier.TransportCourrierXsd;
import com.cpdmali.api.jaxb.courrier.UsersCourrierXsd;

public class CrewIntranetXmlHelper {
	
	public static <T> Object jaxbUnmarshaller(String objectString, String nameObject, Class<T> objectClass) throws JAXBException{
		
		// create JAXB context and initializing Marshaller  
	   JAXBContext jaxbContext = JAXBContext.newInstance(objectClass); 
	   
	   Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
	   
	   InputStream xml = new ByteArrayInputStream(objectString.getBytes());
	   
	   return (T) jaxbUnmarshaller.unmarshal(xml);
		
	}
	
	public static <T> String universalMarshaller(final T object, final String xsdRes, final Class<T> classs, String nameApplication) throws JAXBException, SAXException, InvalidXmlException {
		String xml = null;
		if (object != null) {
			StringWriter sw = new StringWriter();
			JAXBContext jaxbContext = JAXBContext.newInstance(classs.getPackage().getName());
			SchemaFactory schemaFactory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
			Schema schema = schemaFactory.newSchema(CrewIntranetXmlHelper.class.getResource(getSchema(classs, nameApplication)));
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
			marshaller.setSchema(schema);
			marshaller.marshal(object, sw);
			xml = sw.toString();
		}
		return xml;
	}
	
	/**
	 * 
	 * @param classs
	 * @return
	 * @throws InvalidXmlException
	 */
	private static <T> String getSchema(final Class<T> classs, String nameApplication) throws InvalidXmlException {
		String schema = null;

		if (classs.equals(UsersCourrierXsd.class) 
				|| classs.equals(ForwardingCourrierXsd.class)
				|| classs.equals(DomainsCourrierXsd.class)
				|| classs.equals(TransportCourrierXsd.class)) {
			schema = "/schema-xsd/"+nameApplication+"/"+ConstanteHelper.REQUESTEBODY_SHEMA_XSD+".xsd";
//		} else if (classs.equals(IdEmploye.class) || classs.equals(RechercherEmploye.class)) {
//			schema = "/schema-xsd/"+nameApplication+"/requestebody-schema.xsd";
		}  else {
			throw new InvalidXmlException("Schema is unknown");
		}
		return schema;
	}
}
